<template>
	<view class="container">
		<u-navbar
			:is-back="true"
			title="已点歌曲"
			:border-bottom="false"
			@back="goBack"
			:background="{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }"
			title-color="#ffffff"
		/>

		<!-- 加载状态 -->
		<u-loading-page :loading="isLoading" loading-text="正在加载已点歌曲..."></u-loading-page>

		<!-- 主内容区 -->
		<view v-if="!isLoading" class="content-wrapper">
			<!-- 统计信息 -->
			<view v-if="orderedSongs.length > 0" class="stats-bar">
				<view class="stats-item">
					<u-icon name="list" size="24" color="#4ecdc4"></u-icon>
					<text class="stats-text">共 {{ orderedSongs.length }} 首歌曲</text>
				</view>
				<view class="stats-item">
					<u-icon name="clock" size="24" color="#ffa726"></u-icon>
					<text class="stats-text">预计 {{ estimatedTime }} 分钟</text>
				</view>
			</view>

			<!-- 歌曲列表 -->
			<view v-if="orderedSongs.length > 0" class="song-list">
				<view v-for="(song, index) in orderedSongs" class="song-item">
					<!-- 序号 -->
					<view class="song-index">
						<text class="index-number">{{ index + 1 }}</text>
					</view>

					<!-- 歌曲封面 -->
					<!-- <image
						:src="song.cover_url || song.cover || song.pic_url || song.img_url || song.image || song.avatar || '/static/song/default-cover.jpg'"
						class="song-cover"
						mode="aspectFill"
					/> -->

					<!-- 歌曲信息 -->
					<view class="song-info">
						<view class="song-title">{{ song.song_name || song.title }}</view>
						<view class="song-artist">{{ song.singer || song.singer_name || song.artist }}</view>
						<view class="song-status" v-if="song.status">
							<text :class="['status-text', getStatusClass(song.status)]">
								{{ getStatusText(song.status) }}
							</text>
						</view>
					</view>

					<!-- 操作按钮 -->
					<view class="song-actions">
						<view class="action-btn" @click="handlePinSong(song, index)">
							<u-icon name="pushpin" size="32" color="#45b7d1"></u-icon>
							<text class="action-text">置顶</text>
						</view>
						<view class="action-btn" @click="handleRemoveSong(song, index)">
							<u-icon name="trash" size="32" color="#ff6b6b"></u-icon>
							<text class="action-text">删除</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view v-else class="empty-state">
				<view class="empty-icon">🎵</view>
				<view class="empty-title">暂无已点歌曲</view>
				<view class="empty-desc">快去点一首喜欢的歌曲吧~</view>
				<u-button type="primary" shape="round" @click="goToSongPage" class="empty-btn">去点歌</u-button>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view v-if="orderedSongs.length > 0" class="bottom-bar">
			<view class="bottom-actions">
				<!-- <view class="action-item" @click="handleClearAll">
					<u-icon name="trash-fill" size="32" color="#ff6b6b"></u-icon>
					<text class="action-text">清空列表</text>
				</view> -->
				<view class="action-item" @click="handleRefresh">
					<u-icon name="reload" size="32" color="#4ecdc4"></u-icon>
					<text class="action-text">刷新</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import request from '@/common/request.js';
import ktvCommand from '@/common/ktv-command-utils.js';

export default {
	data() {
		return {
			orderId: '',
			isLoading: true,
			orderedSongs: [],
			// 防抖控制
			lastCommandTime: 0,
			commandCooldown: 1000 // 1秒冷却时间
		};
	},
	computed: {
		// 预计播放时间（按每首歌4分钟计算）
		estimatedTime() {
			return Math.ceil(this.orderedSongs.length * 4);
		}
	},
	onLoad(options) {
		this.orderId = options.order_id || '';
		if (!this.orderId) {
			uni.showModal({
				title: '提示',
				content: '缺少订单信息',
				showCancel: false,
				success: () => {
					uni.navigateBack();
				}
			});
			return;
		}
		this.loadOrderedSongs();
	},
	onShow() {
		// 页面显示时刷新数据
		if (this.orderId) {
			this.loadOrderedSongs();
		}
	},
	methods: {
		goBack() {
			uni.navigateBack();
		},

		// 检查是否可以执行命令
		canExecuteCommand() {
			const now = Date.now();
			const timeSinceLastCommand = now - this.lastCommandTime;

			if (timeSinceLastCommand < this.commandCooldown) {
				const remainingTime = Math.ceil((this.commandCooldown - timeSinceLastCommand) / 1000);
				uni.showToast({
					title: `请等待${remainingTime}秒后再操作`,
					icon: 'none',
					duration: 1000
				});
				return false;
			}

			return true;
		},

		// 更新最后命令时间
		updateLastCommandTime() {
			this.lastCommandTime = Date.now();
		},

		// 加载已点歌曲列表
		async loadOrderedSongs() {
			this.isLoading = true;
			try {
				const res = await request.httpTokenRequest({
					url: `/api/ktv/getPintedSong?order_id=${this.orderId}`,
					method: 'get'
				});

				if (res.data.code === 1) {
					this.orderedSongs = res.data.data.song_list || [];
					console.log('获取已点歌曲成功，数量:', this.orderedSongs.length);
				} else {
					throw new Error(res.data.msg || '获取已点歌曲失败');
				}
			} catch (error) {
				console.error('获取已点歌曲失败:', error);
				uni.showToast({
					title: error.message || '获取已点歌曲失败',
					icon: 'none'
				});
				this.orderedSongs = [];
			} finally {
				this.isLoading = false;
			}
		},

		// 置顶歌曲
		async handlePinSong(song, index) {
			if (!this.canExecuteCommand()) return;
			uni.showModal({
				title: '确认置顶',
				content: `确定要将\"${song.song_name || song.title}\"置顶吗？`,
				success: async (res) => {
					if (res.confirm) {
						this.updateLastCommandTime();
						const success = await ktvCommand.insertSong(this.orderId, song.song_id || song.id);
						if (success) {
							uni.showToast({
								title: `已置顶：${song.song_name || song.title}`,
								icon: 'success'
							});
							// 刷新列表
							setTimeout(() => {
								this.loadOrderedSongs();
							}, 1000);
						}
					}
				}
			});
		},

		// 删除歌曲
		handleRemoveSong(song, index) {
			if (!this.canExecuteCommand()) return;
			console.log(song);

			uni.showModal({
				title: '确认删除',
				content: `确定要删除"${song.title}"吗？`,
				success: async (res) => {
					if (res.confirm) {
						this.updateLastCommandTime();
						const songId = song.song_id || song.id;
						const success = await ktvCommand.removeSong(this.orderId, songId);
						if (success) {
							uni.showToast({
								title: `已删除：${song.title}`,
								icon: 'success'
							});
							// 从列表中移除
							this.orderedSongs.splice(index, 1);
						}
					}
				}
			});
		},

		// 清空列表
		handleClearAll() {
			if (this.orderedSongs.length === 0) return;

			uni.showModal({
				title: '确认清空',
				content: '确定要清空所有已点歌曲吗？此操作不可恢复。',
				success: async (res) => {
					if (res.confirm) {
						if (!this.canExecuteCommand()) return;
						this.updateLastCommandTime();

						const success = await ktvCommand.clearAllSongs(this.orderId);
						if (success) {
							uni.showToast({
								title: '已清空歌曲列表',
								icon: 'success'
							});
							this.orderedSongs = [];
						}
					}
				}
			});
		},

		// 刷新列表
		handleRefresh() {
			this.loadOrderedSongs();
			uni.showToast({
				title: '正在刷新...',
				icon: 'loading',
				duration: 1000
			});
		},

		// 跳转到点歌页面
		goToSongPage() {
			// 返回上一页
			uni.navigateBack({
				delta: 1
			});
		},

		// 获取状态样式类
		getStatusClass(status) {
			switch (status) {
				case 'playing':
					return 'status-playing';
				case 'waiting':
					return 'status-waiting';
				case 'finished':
					return 'status-finished';
				default:
					return 'status-default';
			}
		},

		// 获取状态文本
		getStatusText(status) {
			switch (status) {
				case 'playing':
					return '正在播放';
				case 'waiting':
					return '等待播放';
				case 'finished':
					return '已播放';
				default:
					return '未知状态';
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
	background: linear-gradient(180deg, #0d0d11 0%, #1a1a1f 100%);
	color: #ffffff;
	min-height: 100vh;
	padding-bottom: 120rpx;
}

.content-wrapper {
	padding: 20rpx;
}

.stats-bar {
	display: flex;
	justify-content: space-around;
	align-items: center;
	margin-bottom: 30rpx;
	padding: 20rpx;
	background: rgba(255, 255, 255, 0.05);
	border-radius: 15rpx;
	backdrop-filter: blur(10rpx);
	border: 1rpx solid rgba(255, 255, 255, 0.1);
}

.stats-item {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.stats-text {
	font-size: 24rpx;
	color: #ffffff;
}

.song-list {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
}

.song-item {
	display: flex;
	align-items: center;
	background: rgba(255, 255, 255, 0.05);
	border-radius: 15rpx;
	padding: 20rpx;
	backdrop-filter: blur(10rpx);
	border: 1rpx solid rgba(255, 255, 255, 0.1);
	transition: all 0.3s;

	&:active {
		transform: scale(0.98);
		background: rgba(255, 255, 255, 0.1);
	}
}

.song-index {
	width: 50rpx;
	height: 50rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
}

.index-number {
	font-size: 24rpx;
	font-weight: bold;
	color: #ffffff;
}

.song-cover {
	width: 80rpx;
	height: 80rpx;
	border-radius: 12rpx;
	margin-right: 20rpx;
	border: 2rpx solid rgba(255, 255, 255, 0.1);
}

.song-info {
	flex: 1;
	min-width: 0;
}

.song-title {
	font-size: 30rpx;
	font-weight: 500;
	color: #ffffff;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	margin-bottom: 8rpx;
}

.song-artist {
	font-size: 24rpx;
	color: #bfcfff;
	margin-bottom: 5rpx;
}

.song-status {
	margin-top: 5rpx;
}

.status-text {
	font-size: 20rpx;
	padding: 2rpx 8rpx;
	border-radius: 8rpx;
}

.status-playing {
	color: #4ecdc4;
	background: rgba(78, 205, 196, 0.1);
}

.status-waiting {
	color: #ffa726;
	background: rgba(255, 167, 38, 0.1);
}

.status-finished {
	color: #888888;
	background: rgba(136, 136, 136, 0.1);
}

.status-default {
	color: #cccccc;
	background: rgba(204, 204, 204, 0.1);
}

.song-actions {
	display: flex;
	gap: 15rpx;
}

.action-btn {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 5rpx;
	padding: 10rpx;
	border-radius: 12rpx;
	transition: all 0.3s;

	&:active {
		transform: scale(0.9);
		background: rgba(255, 255, 255, 0.1);
	}
}

.action-text {
	font-size: 20rpx;
	color: #ffffff;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 40rpx;
	text-align: center;
}

.empty-icon {
	font-size: 120rpx;
	margin-bottom: 30rpx;
}

.empty-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #ffffff;
	margin-bottom: 15rpx;
}

.empty-desc {
	font-size: 26rpx;
	color: #888888;
	margin-bottom: 40rpx;
}

.empty-btn {
	width: 200rpx;
}

.bottom-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: rgba(255, 255, 255, 0.05);
	backdrop-filter: blur(20rpx);
	border-top: 1rpx solid rgba(255, 255, 255, 0.1);
	padding: 20rpx;
}

.bottom-actions {
	display: flex;
	justify-content: space-around;
	align-items: center;
}

.action-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8rpx;
	padding: 15rpx;
	border-radius: 12rpx;
	transition: all 0.3s;

	&:active {
		transform: scale(0.9);
		background: rgba(255, 255, 255, 0.1);
	}
}
</style>